import { generateOrderNumber, isPro, sleep } from '@libs/common/utils';
import { Injectable } from '@nestjs/common';
import { Cron } from '@nestjs/schedule';

import {
  ApiAtmDeliver,
  ApiAtmLight,
  ApiAtmOrderShow,
  DeliverOrderDetail,
} from './deliver.api';
import { DeliverDto } from './dto/deliver.dto';

@Injectable()
export class DeliverService {
  /** 兑换机交货 */
  async deliver(dto: DeliverDto) {
    if (isPro) {
      return ApiAtmDeliver(dto);
    }
    return dto.transNo;
  }

  async order(
    mcuid: string,
    transNo: string,
  ): Promise<DeliverOrderDetail | null> {
    if (isPro) {
      return ApiAtmOrderShow(transNo, mcuid);
    }
    return { result: 1 } as DeliverOrderDetail;
  }

  async checkOrderResult(
    transNo: string,
    mcuid: string,
    count: number = 0,
  ): Promise<DeliverOrderDetail | null> {
    let data: DeliverOrderDetail | null = null;
    if (count === 0) await sleep(3000);

    await sleep(2000);

    console.log('开始查询订单 :>> ', transNo, count);
    data = await this.order(mcuid, transNo);

    const result = data?.result === 1;
    console.log('结束查询订单 :>> ', data);

    if (!result && ++count < 10) {
      return await this.checkOrderResult(transNo, mcuid, count);
    }

    return data;
  }

  // 每天 8:50 执行
  @Cron('0 50 8 * * *')
  private handleOpenMorning() {
    // ApiAtmLight(5);
  }

  // 每天 14:10 执行
  @Cron('0 10 14 * * *')
  private handleOpenAfternoon() {
    // ApiAtmLight(5);
  }

  // 每天 12:40 执行
  @Cron('0 40 12 * * *')
  private handleCloseMorning() {
    // ApiAtmLight(1);
  }

  // 每天 19:00 执行
  @Cron('0 0 19 * * *')
  private handleCloseAfternoon() {
    // ApiAtmLight(1);
  }
}
